﻿using UnityEngine;
using System.Collections;

public class CubeTouch : MonoBehaviour, ICube {
	
	public Material[] materials;
	public int tagPos;
	public string cubeName;
	
	private Renderer rend;
	private bool on;
	
	// Use this for initialization
	void Start () {
		// Debug.Log (GameManager.getInstance ());
		GameManager.getInstance ().registerForCubeNotifications (this);
		on = GameManager.getInstance ().getCubeStartConfig (tagPos);
		rend = GetComponent<Renderer> ();
		rend.material = materials [(on) ? 1 : 0];
	}

	void OnDestroy() {
		GameManager.getInstance ().deregisterForCubeNotifications (this);
	}

	// Update is called once per frame
	void Update () {
		if (Application.platform == RuntimePlatform.Android) {
			if(Input.touchCount > 0) {
				if(Input.GetTouch(0).phase == TouchPhase.Began) {
					CheckTouch(Input.GetTouch(0).position, "began");
				} else if(Input.GetTouch(0).phase == TouchPhase.Ended) {
					CheckTouch(Input.GetTouch(0).position, "ended");
				}
			}
		}
		
		if (Application.platform == RuntimePlatform.WindowsEditor) {
			if(Input.GetMouseButtonDown(0)) {
				CheckTouch(Input.mousePosition, "began");
			}
			if(Input.GetMouseButtonUp(0)) {
				CheckTouch(Input.mousePosition, "ended");
			}
		}
	}

	void ChangeState(bool updateOthers) {
		on = !on;
		rend.material = materials[(on) ? 1 : 0];
		GameManager.getInstance ().CubeUpdateState (tagPos, on);
		if(updateOthers) GameManager.getInstance().CubeClicked(tagPos);
	}
	
	void CheckTouch(Vector3 pos, string phase) {
		if (GameManager.getInstance ().GetFinished () != 0)
			return; // we have finished the game already

		Vector3 wp = Camera.main.ScreenToWorldPoint (pos);
		Vector2 touchPos = new Vector2 (wp.x, wp.y);
		Collider2D hit = Physics2D.OverlapPoint (touchPos);
		
		if (hit == null) // touch didn't hit any collider
			return;

		if (hit.gameObject.name == cubeName && phase == "began") {
			ChangeState(true);
		}
	}

	public void CheckAdjacent(int x, int y) {
		int myX = tagPos / 10;
		int myY = tagPos % 10;

		if (myX == x && myY == y) // they are in the same position, so we've already changed states
			return;
		int xDiff = Mathf.Abs (myX - x); // x coord is within 1
		int yDiff = Mathf.Abs (myY - y); // y coord is within 1

		if ((xDiff == 0 && yDiff == 1) || // we are adjacent in x direction XOR y direction
			(xDiff == 1 && yDiff == 0)) {
			ChangeState(false);
		}
	}

	public void Reset() {
		on = GameManager.getInstance ().getCubeStartConfig (tagPos);
		rend = GetComponent<Renderer> ();
		rend.material = materials [(on) ? 1 : 0];
	}
}
